package com.leyou.auth.service.impl;

import com.leyou.auth.constants.RedisConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import feign.FeignException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("ALL")
/**
 * @Description :
 * @author     :LD
 */
@Service
public class UserAuthServiceImpl implements UserAuthService {
    @Autowired
    private UserClient userClient;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void login(String username, String password, HttpServletResponse response) {
        try {
            //远程调用user，查询数据
            UserDTO userDTO = userClient.queryUserByUsernameAndPassword(username, password);
            if (userDTO==null){
                throw new LyException(400,"用户名或密码错误");
            }
            //生成token
            String toekn = jwtUtils.createJwt(UserDetail.of(userDTO.getId(), userDTO.getUsername()));
            //将token放入到cookie中返回
            writeCookie(response,toekn);
        } catch (FeignException e) {
            //将远程调用过程中的异常抛出
            throw new LyException(e.status(),e.contentUTF8());
        }
    }

    private void writeCookie(HttpServletResponse response, String toekn) {
        Cookie cookie = new Cookie(JwtConstants.COOKIE_NAME, toekn);
        //设置域
        cookie.setDomain(JwtConstants.DOMAIN);
        // 是否禁止JS操作cookie，避免XSS攻击
        cookie.setHttpOnly(true);
        // cookie有效期，-1就是跟随当前会话，浏览器关闭就消失
        cookie.setMaxAge(-1);
        // cookie作用的路径，/代表一切路径
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        //获取cookier
        String cookieValue = CookieUtils.getCookieValue(request, JwtConstants.COOKIE_NAME);
        //校验token有效性
        Payload payload=null;
        try {
            payload = jwtUtils.parseJwt(cookieValue);
        } catch (Exception e) {
            //token无效时，直接返回
            return;
        }
        //token有效，
        //1删除cookie
        CookieUtils.deleteCookie(JwtConstants.COOKIE_NAME,JwtConstants.DOMAIN,response);
        // 2删除redis中的数据
        redisTemplate.delete(RedisConstants.JTI_KEY_PREFIX+payload.getUserDetail().getId());
    }
}
